package com.thinkgem.jeesite.modules.mobile.service;

import com.alibaba.fastjson.JSONObject;
import com.ckfinder.connector.utils.FileUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.ResponseResult;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipment;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipmentLog;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipmentType;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentLogService;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentService;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentTypeService;
import com.thinkgem.jeesite.modules.messages.entity.EleEquipmentMessages;
import com.thinkgem.jeesite.modules.messages.service.EleEquipmentMessagesService;
import com.thinkgem.jeesite.modules.source.entity.EleSourceGroup;
import com.thinkgem.jeesite.modules.source.service.EleSourceGroupService;
import com.thinkgem.jeesite.modules.sys.MessagesUtils;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.SwitchUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.templet.entity.EleTemplet;
import com.thinkgem.jeesite.modules.templet.service.EleTempletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * @author John
 * @Date 2017-06-07
 */
@Controller
@RequestMapping(value = "${adminPath}/mobile")
public class MobileInterFaceService extends BaseController{

    @Autowired
    private SystemService systemService;
    @Autowired
    private EleTempletService eleTempletService;
    @Autowired
    private EleSourceGroupService eleSourceGroupService;
    @Autowired
    private EleEquipmentService eleEquipmentService;

    @Autowired
    private EleEquipmentTypeService eleEquipmentTypeService;
    @Autowired
    private OfficeService officeService;

    @Autowired
    private EleEquipmentMessagesService eleEquipmentMessagesService;

    @Autowired
    private EleEquipmentLogService eleEquipmentLogService;

    @RequestMapping("findpassword")
    @ResponseBody
    public Result find(String username){
        List<User> areaadmins = new ArrayList<>();

        User user = new User();
        user.setName(username);
        List<User> users = systemService.findList(user);

        String result;
        String message;
        if(null == users || users.isEmpty()){
            result = Result.FAILURE;
            message = "用户名或者账号不正确,没有查询到该用户!";
        }
        else if(users.size() >= 2){
            result = Result.FAILURE;
            message = "查询到超过两名用户,请使用手机号查询!";
        }
        else{
            result = Result.SUCCESS;
            message = "成功!";
            User temuser = users.get(0);
            String enname = temuser.getRole().getEnname();
            Office company = temuser.getCompany();
            // 区域管理员忘记密码找管理员
            if("areaadmin".equals(enname)){
                User admin = systemService.getUser("u_1");
                areaadmins.add(admin);
            }
            else if("admin".equals(enname)){
                areaadmins.add(temuser);
            }
            // 其他用户忘记密码找 区域管理员
            else{
                User usera = new User();
                usera.setCompany(company);
                usera.setRole(new Role("2"));
                areaadmins = systemService.findList(usera);
            }
        }

        return new Result(result, message, areaadmins);
    }

    /**
     * 查询用户信息
     * @param token
     * @return
     */
    @RequestMapping(value = "userinfo")
    @ResponseBody
    public Result userinfo(String token){
        User temuser = UserUtils.getByToken(token);

        if(null == temuser.getId()){
            return new Result(Result.NO_LOGIN, "用户未登录!", null);
        }
        else{
            User admin = UserUtils.getAdminUser();
            JSONObject current = new JSONObject();
            current.put("user", temuser);
            current.put("admin", admin);

            return new Result(Result.SUCCESS, "成功", current);
        }
    }


    /**
     * 修改个人用户密码
     *
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping(value = "modifyPwd")
    @ResponseBody
    public Result modifyPwd(String token, String oldPassword, String newPassword){
        User user = UserUtils.getByToken(token);
        if(null == user.getId()){
            return new Result(Result.NO_LOGIN, "用户未登录!", null);
        }
        else{
            String result;
            String message;
            if(StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
                if(SystemService.validatePassword(oldPassword, user.getPassword())){
                    systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
                    message = "修改密码成功!";
                    result = Result.SUCCESS;
                }
                else{
                    message = "修改密码失败，旧密码错误!";
                    result = Result.FAILURE;
                }
            }
            else{
                message = "新旧密码不能为空!";
                result = Result.FAILURE;
            }
            return new Result(result, message, null);
        }
    }

    @RequestMapping("equipmentlist")
    @ResponseBody
    public Result list(String token, String mac){
        User current = UserUtils.getByToken(token);
        if(null == current.getId()){
            return new Result(Result.NO_LOGIN, "用户未登录!", null);
        }
        else{
            EleEquipment eleEquipment = new EleEquipment();
            eleEquipment.setCode(mac);

            List<Office> listTree = new ArrayList<>();
            List<User> resultList = (List<User>)getBranchForUser(token).getData();
            Set<String> ids = new HashSet<String>();
            for(User temuser : resultList){
                String officeId = temuser.getOffice().getId();
                String companyId = temuser.getCompany().getId();
                ids.add(officeId);
                ids.add(companyId);
            }
            List<Office> listOffice = officeService.findList(true);
            Set<String> resultSet = new HashSet<String>();
            for(String oid : ids){
                resultSet.add(oid);
                Office tmp = officeService.get(oid);
                for(int i = 0; i < listOffice.size(); i++){
                    Office item = listOffice.get(i);
                    if(item.getId().equals(tmp.getParentId())){
                        System.out.println(item);
                        tmp = item;
                        i = -1;
                        resultSet.add(item.getId());
                    }
                }
            }
            for(String oid : resultSet){
                Office item = officeService.get(oid);
                item.setAddress(null);
                item.setEmail(null);
                item.setFax(null);
                item.setRemarks(null);
                item.setPhone("display:none;");
                listTree.add(item);
            }
            Set<String> eqIds = new HashSet<>();
            for(User tmp : resultList){
                EleEquipment eleEquipmentTmp = new EleEquipment();
                eleEquipmentTmp.setCompany(tmp.getCompany());
                eleEquipmentTmp.setOffice(tmp.getOffice());

                List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipment);
                for(EleEquipment equipment : listEquipment){
                    if(eqIds.contains(equipment.getId())){
                        continue;
                    }
                    eqIds.add(equipment.getId());
                    Office Office = new Office();
                    Office.setId(equipment.getId());
                    Office.setParent(new Office(equipment.getOffice().getId()));
                    Office.setAddress(equipment.getCode());
                    Office.setEmail(equipment.getType().getName());
                    Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
                    Office.setRemarks(equipment.getRemarks());
                    Office.setPhone("");
                    listTree.add(Office);
                }
            }
            return new Result(listTree);
        }
    }

    @RequestMapping(value = "equipmentType")
    @ResponseBody
    public Result treeData(String token){
        User thisuser = UserUtils.getByToken(token);
        if(null == thisuser.getId()){
            return new Result(Result.NO_LOGIN, "用户未登录!", null);
        }
        else{
            List<EleEquipmentType> list = eleEquipmentTypeService.findList(new EleEquipmentType());
            return new Result(list);
        }
    }

    /**
     * 上报设备
     *
     * @param code
     * @param company
     * @param office
     * @param type
     * @param width
     * @param height
     * @return
     */
    @RequestMapping(value = "equipmentAdd")
    @ResponseBody
    public Result add(String token, String code, String company, String office, String type, int width, int height){
        User thisuser = UserUtils.getByToken(token);
        if(null == thisuser.getId()){
            return new Result(Result.NO_LOGIN, "用户未登录!", null);
        }
        else{
            EleEquipment eleEquipment = eleEquipmentService.findEquipmentByCode(code);
            if(null == eleEquipment
                || EleEquipment.DEL_FLAG_DELETE.equals(eleEquipment.getDelFlag())
                || EleEquipment.DEL_FLAG_AUDIT_NO.equals(eleEquipment.getDelFlag())){
                eleEquipment = new EleEquipment();
                eleEquipment.setCode(code);
                if(StringUtils.isEmpty(company)){
                    return new Result(Result.FAILURE, "设备所在分公司不能为空!", null);
                }
                else{
                    eleEquipment.setCompany(new Office(company));
                }
                if(StringUtils.isEmpty(office)){
                    return new Result(Result.FAILURE, "设备所在分组不能为空!", null);
                }
                else{
                    eleEquipment.setOffice(new Office(office));
                }

                eleEquipment.setType(new EleEquipmentType(type));
                eleEquipment.setWidth(width);
                eleEquipment.setHeight(height);
                eleEquipment.setCreateBy(UserUtils.getUser());
                eleEquipment.setCheckDate(new Date());

                String message;
                // 审核控制没有关闭 并且没有用户权限的时候
                String enname = thisuser.getRole().getEnname();
                if(!("admin".equals(enname) || "areaadmin".equals(enname)) && !SwitchUtils.isClose("equipment:eleEquipment:check")){
                    eleEquipment.setCheckBy(UserUtils.getCheckUser("", thisuser));
                    eleEquipment.setDelFlag(EleEquipment.DEL_FLAG_AUDIT);
                    message = "设备添加成功,等待区域管理员审核!";
                }
                else{
                    eleEquipment.setCheckBy(thisuser);
                    eleEquipment.setDelFlag(EleEquipment.DEL_FLAG_NORMAL);
                    message = "设备添加成功!";
                }

                try{
                    eleEquipmentService.save(eleEquipment);
                    return new Result(Result.SUCCESS, message, null);
                }
                catch(Exception e){
                    logger.error("保存设备信息失败:", e);
                    return new Result(Result.FAILURE, "", null);
                }
            }
            else if(EleEquipment.DEL_FLAG_AUDIT.equals(eleEquipment.getDelFlag())){
                return new Result(Result.FAILURE, "设备已经添加,等待审核!", null);
            }
            else{
                return new Result(Result.FAILURE, "设备已经存在!", null);
            }
        }
    }

    @RequestMapping("templet")
    @ResponseBody
    public Result templet(String token, String remarks, HttpServletRequest request, HttpServletResponse response){
        response.setContentType("application/json; charset=UTF-8");
        User thisuser = UserUtils.getByToken(token);
        if(null == thisuser.getId()){
            return new Result(Result.NO_LOGIN, "用户未登录!", null);
        }
        else{
            EleTemplet eleTemplet = new EleTemplet();
            eleTemplet.setRemarks(remarks);
            Page<EleTemplet> page = eleTempletService.findPage(new Page<EleTemplet>(request, response), eleTemplet);

            List<EleTemplet> list = page.getList();
            for(EleTemplet templet:list){
                String templateId = templet.getId();
                String basePath = DictUtils.getDictValue("basePath", "systemvalue", "");
                String zipPath = basePath + "/theme/source/"+templateId+"/"+templateId+".zip";
                templet.setUrl(zipPath);
            }
            page.setList(list);
            return new Result(Result.SUCCESS, "", page);
        }
    }

    @RequestMapping("source")
    @ResponseBody
    public Result source(String token, String remarks, HttpServletRequest request, HttpServletResponse response){
        response.setContentType("application/json; charset=UTF-8");
        User thisuser = UserUtils.getByToken(token);
        if(null == thisuser.getId()){
            return new Result(Result.NO_LOGIN, "用户未登录!", null);
        }
        else{
            EleSourceGroup sourceGroup = new EleSourceGroup();
            sourceGroup.setRemarks(remarks);
            Page<EleSourceGroup> page = eleSourceGroupService.findPage(new Page<EleSourceGroup>(request, response), sourceGroup);

            List<EleSourceGroup> list = page.getList();
            for(EleSourceGroup source:list){
                String groupId = source.getId();
                String basePath = DictUtils.getDictValue("basePath", "systemvalue", "");
                String zipPath = basePath + "/theme/source/"+groupId+"/"+groupId+".zip";
                source.setUrl(zipPath);
            }
            page.setList(list);
            return new Result(Result.SUCCESS, "", list);
        }
    }

    @RequestMapping("userbranchuser")
    @ResponseBody
    private Result getBranchForUser(String token){
        User current = UserUtils.getByToken(token);

        if(null == current.getId()){
            return new Result(Result.NO_LOGIN, "用户未登录!", null);
        }
        else{
            List<User> list = systemService.findList(new User());
            Role role = current.getRole();
            List<User> resultList = new ArrayList<>();
            if(null != role){
                if(role.getEnname().equals("admin")){
                    resultList = list;
                }
                else if(role.getEnname().equals("user")){
                    resultList.add(current);
                }
                else if(role.getEnname().equals("operate")){
                    for(User usr : list){
                        if(usr.getRole().getEnname().equals("user")
                                && usr.getCompany().getId().equals(current.getOffice().getId())){
                            resultList.add(usr);
                        }
                    }
                    resultList.add(current);
                }
                else{
                    Set<String> offices = new HashSet<>();
                    for(User usr : list){
                        if(usr.getRole().getEnname().equals("operate")
                                && usr.getCompany().getId().equals(current.getOffice().getId())){
                            resultList.add(usr);
                            offices.add(usr.getOffice().getId());
                        }
                    }
                    offices.add(current.getOffice().getId());
                    for(User usr : list){
                        if(usr.getRole().getEnname().equals("user") && offices.contains(usr.getCompany().getId())){
                            resultList.add(usr);
                        }
                    }
                    resultList.add(current);
                }
                return new Result(Result.SUCCESS, "用户未登录!", resultList);
            }else{
                return new Result(Result.FAILURE, "用户角色没有设置,请联系管理员!", null);
            }
        }
    }

    /**
     * 获取该用户可访问的分公司、分组
     *
     * @param token
     * @return
     */
    @RequestMapping("userbranchoffice")
    @ResponseBody
    private Result userbranchoffice(String token){
        User current = UserUtils.getByToken(token);
        if(null == current.getId()){
            return new Result(Result.NO_LOGIN, "用户没有登录!", null);
        }
        else{
            String userCompanyId = current.getCompany().getId();
            String userOfficeId = current.getOffice().getId();
            List<Office> officeList = officeService.findList(true);
            List<Office> temOfficeList = new ArrayList<>();
            if(!current.isAdmin()){
                for(Office office:officeList){
                    // 公司
                    if("1".equals(office.getType())){
                        if(office.getId().equals(userCompanyId)){
                            temOfficeList.add(office);
                        }
                        else if(office.getParentIds().contains(userCompanyId)){
                            temOfficeList.add(office);
                        }
                    }
                    else if("2".equals(office.getType())){
                        if(office.getId().equals(userOfficeId)){
                            temOfficeList.add(office);
                        }
                        else if(office.getParentIds().contains(userOfficeId)){
                            temOfficeList.add(office);
                        }
                    }
                }
                officeList = temOfficeList;
            }
            return new Result(officeList);
        }
    }

    /**
     * 查询设备连接记录
     * @param id
     * @param mac
     * @param size
     * @param token
     * @return
     */
    @RequestMapping("connectRecord")
    @ResponseBody
    private Result connectRecord(String id, String mac, String token, HttpServletRequest request, HttpServletResponse response){
        User current = UserUtils.getByToken(token);
        if(null == current.getId()){
            return new Result(Result.NO_LOGIN, "用户没有登录!", null);
        }else{
            EleEquipmentMessages condation = new EleEquipmentMessages();
            condation.setId(id);
            condation.setType("connect");
            condation.setMethod("request");
            condation.setMac(mac);

            Page<EleEquipmentMessages> page = eleEquipmentMessagesService.findPage(new Page<EleEquipmentMessages>(request, response), condation);
            return new Result(page);
        }
    }

    /**
     * 上传pad 连接设备的记录
     * @param mac 设备编号
     * @param time 连接时间
     * @param token 用户token
     * @return
     */
    @RequestMapping("reportConnectRecord")
    @ResponseBody
    private Result reportConnectRecord(String mac, Long time, String token){
        User current = UserUtils.getByToken(token);
        if(null == current.getId()){
            return new Result(Result.NO_LOGIN, "用户没有登录!", null);
        }else{
            MessagesUtils.saveMessages("connect", "", "request", ResponseResult.SUCCESS, mac, "设备连接记录", time);
            return new Result(null);
        }
    }

    /**
     * 上报设备日志
     * @param mac
     * @param filename
     * @param file
     * @param token
     * @return
     */
    @RequestMapping(value = "uploadEquipmentLog")
    @ResponseBody
    public Result uploadEquipmentLog(String mac, String filename, MultipartFile file,String token){
        User current = UserUtils.getByToken(token);
        if(null == current.getId()){
            return new Result(Result.NO_LOGIN, "用户没有登录!", null);
        }
        else{
            EleEquipment eleEquipment = eleEquipmentService.findEquipmentConfigByCode(mac);
            String dirPath = Global.getUserfilesBaseDir() + "upload/app/";
            String fullPath = Global.getUserfilesBaseDir() + "upload/app/" + filename;
            String filePath = "upload/app/" + filename;
            if(file != null){
                // 转存文件
                try{
                    File dir = new File(dirPath);
                    if(!dir.exists() && dir.isDirectory()){
                        dir.mkdirs();
                    }
                    File tmp = new File(fullPath);
                    if(tmp.exists()){
                        FileUtils.delete(tmp);
                    }
                    File log = new File(fullPath);
                    file.transferTo(log);
                }
                catch(Exception e){
                    e.printStackTrace();
                }

                EleEquipmentLog log = eleEquipmentLogService.findLogByPath(filePath);
                if(log == null){
                    log = new EleEquipmentLog();
                    log.setEquipmentId(eleEquipment.getId());
                    log.setType("app");
                    log.setPath(filePath);
                    log.setName(filename);
                    eleEquipmentLogService.save(log);
                }
                return new Result(null);
            }
            else{
                return new Result(Result.FAILURE, "", null);
            }
        }
    }
}
